/*
 * Open LiveReplay Server - Live replay server for Supreme Commander
 * 
 * Copyright (C) 2009, 2009 Open LiveReplay Server Project
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details:
 * http://www.gnu.org/copyleft/lesser.html#TOC3
 */
package net.galacticwar.replayserver;

import java.util.logging.Level;
import java.util.logging.Logger;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.mina.common.IoSession;

/**
 * 
 * A very basic JMX implementation for Server management
 * 
 * @author Yoann Meste (aka Mancer)
 *
 */
public class ServerManager implements ServerManagerMBean {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ServerManager.class.getName());

	private final Map<String, LiveReplay> replays;
	
	public ServerManager(Map<String, LiveReplay> replays) {
		this.replays = replays;
	}
	
	@Override
	public void closeServer(boolean forced) {

		if (logger.isLoggable(Level.INFO)) {
			logger.log(Level.INFO, "Server shutdown requested...");
		}

		if (forced) {
			System.exit(0);
		}
		
		else{
			
		}
		
	}
	
	
	
	@Override
	public String[] getReplayListeners(String replayName) {
		LiveReplay replay = replays.get(replayName);
		if (replay == null) {
			return new String[]{"Replay not found"};
		}
		
		Set<IoSession> sessions = replay.getListeners();
		
		String[] names = new String[sessions.size()];
		int i=0;
		for (IoSession session : sessions) {
			names[i] = session.getRemoteAddress().toString();
			i++;
		}
		return names;
	}

	@Override
	public String[] getReplays() {
		String[] names = new String[replays.size()];
		int i=0;
		for (LiveReplay replay : replays.values()) {
			names[i] = replay.getName();
			i++;
		}
		return names;
	}

	@Override
	public String loadReplay(String fileName) {
		File file = new File(fileName);
		if (file.exists() == false) {
			return "The file " + fileName + " doesn't exists !";
		}
		
		try {
			LiveReplay replay  = new LiveReplay(file);
			replays.put(file.getName(), replay);
		} catch (IOException e) {
			return "Error during loading file " + fileName + " " + e.getMessage();
		}

		return "Replay file " + fileName + " loaded succesfully";
	}
	
	@Override
	public String closeReplay(String fileName, boolean forced) {
		LiveReplay replay = replays.get(fileName);
		if (replay == null) {
			return "The replay " + fileName + " doesn't exists !";
		}
		
		if (forced == false && replay.getListeners().size()!= 0) {
			return "Impossible to close this replay. Some players are still watching this replay";
		}
		
		if (forced == false && replay.isInProgress()) {
			return "Impossible to close this replay. This replay is in progress";
		}
		
		replay.close();
		replays.remove(fileName);
		
		return "Replay closed succesfully";
	}
	
	@Override
	public String getReplayDetails(String replayName) {
		LiveReplay replay = replays.get(replayName);
		if (replay == null) {
			return "The replay " + replayName + " doesn't exists !";
		}
		
		StringBuilder sb = new StringBuilder();
		sb.append("Replay name=");
		sb.append(replay.getName());
		
		sb.append(" Started on ");
		sb.append(replay.getStartingDate());
		
		sb.append(" Map : ");
		sb.append(replay.getReplay().getMap());

		sb.append(" players = ");
		for (Player player : replay.getReplay().getPlayers()) {
			sb.append(player.getName());
			sb.append(",");
		}
		
		return sb.toString();

	}
	
	@Override
	public boolean isReplayFilterActive() {
		return ReplayFilter.getInstance().isEnabled();
	}

	@Override
	public void setReplayFilterActive(boolean active) {
		ReplayFilter.getInstance().setEnabled(active);
	}

	@Override
	public String registerPlayer(String playerName) {
		ReplayFilter.getInstance().registerName(playerName);
		return "Player " + playerName + " allowed to send replay";
	}

	@Override
	public String unregisterPlayer(String playerName) {
		ReplayFilter.getInstance().unRegisterName(playerName);
		return "Player " + playerName + " is not allowed to send replay";
	}
	
	@Override
	public String[] getRegisteredPlayers() {
		List<String> registeredList = ReplayFilter.getInstance().getAllowedNames();
		String[] names = new String[registeredList.size()];
		return registeredList.toArray(names);
	}

}
